package com.tim.app.ui.view;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.application.library.net.StringResponseCallback;
import com.application.library.runtime.event.EventManager;
import com.application.library.util.TimeUtil;
import com.application.library.widget.RatioImageView;
import com.application.library.widget.roundimg.RoundedImageView;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.tim.app.R;
import com.tim.app.constant.AppKey;
import com.tim.app.constant.EventTag;
import com.tim.app.server.api.API_User;
import com.tim.app.server.entry.ActionStateMsg;
import com.tim.app.server.entry.Story;
import com.tim.app.server.logic.UserManager;
import com.tim.app.server.net.ServerAddressManager;
import com.tim.app.server.result.ActionResult;
import com.tim.app.server.result.CollectResult;
import com.tim.app.server.result.ResponseResult;
import com.tim.app.share.CustomShareBoard;
import com.tim.app.util.ToastUtil;
import com.tim.app.util.ViewGT;

import java.util.List;
import java.util.Locale;

import jp.wasabeef.glide.transformations.BlurTransformation;

/**
 * 故事详情的header
 */

public class StoryHeadView extends LinearLayout implements View.OnClickListener, SeekBar.OnSeekBarChangeListener {

    public static final String TAG = "StoryHeadView";

    private TextView tvPublishTime;
    private TextView tvPvCount;
    private TextView tvUserStory;

    RelativeLayout rivStoryContainer;
    private RatioImageView rivStoryBg;
    private RatioImageView rivStoryGaussBg;
    private RoundedImageView rivStoryImage;

    private TextView tvCurrentTime;
    private SeekBar sbStory;
    private TextView tvTotalTime;

    private ImageView ivPlay;
    private ImageView ivPrevious;
    private ImageView ivNext;
    private ImageView ivPlayList;

    private Story story;
    private List<Story> dataList;
    private int index;

    private View rlActionCollect;
    private TextView tvPriseCount;
    private ImageView ivActionCollect;
    private View rlActionPrise;
    private ImageView ivActionPrise;
    private View rlActionShare;
    private View rlActionComment;
    private TextView tvCommentCount;

    private Activity activity;

    ObjectAnimator animator;

    public StoryHeadView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        tvPublishTime = (TextView) findViewById(R.id.tvPublishTime);
        tvPvCount = (TextView) findViewById(R.id.tvPvCount);
        rivStoryContainer = (RelativeLayout) findViewById(R.id.rivStoryContainer);
        rivStoryBg = (RatioImageView) findViewById(R.id.rivStoryBg);
        rivStoryGaussBg = (RatioImageView) findViewById(R.id.rivStoryGaussBg);
        rivStoryImage = (RoundedImageView) findViewById(R.id.rivStoryImage);
        tvUserStory = (TextView) findViewById(R.id.tvUserStory);

        rlActionCollect = findViewById(R.id.rlActionCollect);
        tvPriseCount = (TextView) findViewById(R.id.tvPriseCount);
        ivActionCollect = (ImageView) findViewById(R.id.ivActionCollect);

        rlActionPrise = findViewById(R.id.rlActionPrise);
        ivActionPrise = (ImageView) findViewById(R.id.ivActionPrise);

        rlActionShare = findViewById(R.id.rlActionShare);

        rlActionComment = findViewById(R.id.rlActionComment);
        tvCommentCount = (TextView) findViewById(R.id.tvCommentCount);

        tvCurrentTime = (TextView) findViewById(R.id.tvCurrentTime);
        sbStory = (SeekBar) findViewById(R.id.sbStory);
        tvTotalTime = (TextView) findViewById(R.id.tvTotalTime);

        ivPlay = (ImageView) findViewById(R.id.ivPlay);
        ivPrevious = (ImageView) findViewById(R.id.ivPrevious);
        ivNext = (ImageView) findViewById(R.id.ivNext);
        ivPlayList = (ImageView) findViewById(R.id.ivPlayList);

        ivPrevious.setOnClickListener(this);
        ivPlay.setOnClickListener(this);
        ivNext.setOnClickListener(this);
        ivPlayList.setOnClickListener(this);

        rlActionCollect.setOnClickListener(this);
        rlActionPrise.setOnClickListener(this);
        rlActionShare.setOnClickListener(this);
        rlActionComment.setOnClickListener(this);

        sbStory.setOnSeekBarChangeListener(this);

        animator = ObjectAnimator.ofFloat(rivStoryContainer, "rotation", 0f, 359.0f);
        LinearInterpolator lin = new LinearInterpolator();
        animator.setDuration(25000);
        animator.setInterpolator(lin);
        animator.setRepeatCount(-1);//设置动画重复次数
        animator.setRepeatMode(ValueAnimator.RESTART);//动画重复模式

        mHandler = new Handler();
        priseTask = new PriseTask();
    }

    /**
     * +
     * 刷新页面
     */
    public void setData(final Activity activity, final List<Story> storyList, int index) {
        if (null == storyList || index > storyList.size())
            return;
        this.story = storyList.get(index);
        this.dataList = storyList;
        this.index = index;
        this.activity = activity;
        if (null != story.getUserMsg()) {
            if (!TextUtils.isEmpty(story.getTitle())) {
                tvUserStory.setVisibility(View.VISIBLE);
                tvUserStory.setText(story.getTitle());
            } else {
                tvUserStory.setVisibility(View.GONE);
            }
        }

        if (null != story.getActionStateMsg()) {
            if (null != story.getActionStateMsg().getAgreeState()) {
                ivActionPrise.setSelected(true);
                initPrise = true;
                isPrise = true;
            } else {
                ivActionPrise.setSelected(false);
            }
            if (null != story.getActionStateMsg().getCollentState()) {
                ivActionCollect.setSelected(true);
            } else {
                ivActionCollect.setSelected(false);
            }
        } else {
            ivActionCollect.setSelected(false);
            ivActionPrise.setSelected(false);
        }
        tvPvCount.setText(getContext().getString(R.string.playCount, String.valueOf(story.getPvCount())));
        tvCommentCount.setText(String.valueOf(story.getCommentCount()));
        tvPriseCount.setText(String.valueOf(story.getAgreeCount()));
        tvPublishTime.setText(TimeUtil.formatTimeRuleOne(getContext(), story.getCreateTime()));
        if (!TextUtils.isEmpty(story.getTime())) {
            tvTotalTime.setText(story.getTime());
        }
        Glide.with(activity)
                .load(story.getImage()).into(rivStoryImage);
        Glide.with(activity)
                .load(story.getImage()).into(rivStoryBg);
        Glide.with(activity)
                .load(story.getImage())
                .bitmapTransform(new BlurTransformation(getContext(), AppKey.DETIAL_RADIUS))//高斯模糊
                .into(rivStoryGaussBg);
        if (!isLoad) {
            ivPlay.performClick();
            isLoad = true;
        }
    }

    boolean isLoad = false;
    int progress;

    @Override
    public void onProgressChanged(SeekBar seekBar, int progressValue, boolean fromUser) {
        this.progress = progressValue * total
                / seekBar.getMax();
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        EventManager.ins().sendEvent(EventTag.GO_PROCESS, seekBar.getProgress(), 0, null);
    }

    private static String generateTime(long time) {
        int totalSeconds = (int) (time / 1000);

        int seconds = totalSeconds % 60;
        int minutes = (totalSeconds / 60) % 60;
        int hours = totalSeconds / 3600;

        if (hours > 0) {
            return String.format(Locale.US, "%02d:%02d:%02d", hours, minutes,
                    seconds).toString();
        } else {
            return String.format(Locale.US, "%02d:%02d", minutes, seconds)
                    .toString();
        }
    }

    /**
     * 更新点赞数量
     */
    public void updateStoryPriseCount() {
        tvPriseCount.setText(String.valueOf(story.getAgreeCount()));
    }

    /**
     * 更新评论数量
     */
    public void updateStoryCommentCount(Story story) {
        if (null == story) {
            return;
        }
        this.story = story;
        tvCommentCount.setText(String.valueOf(story.getCommentCount()));
    }

    public void onPause() {
        state = STATE_PAUSE;
        ivPlay.setBackgroundResource(R.drawable.btn_player_selector_bg);
        animator.pause();
    }

    public void onComplete() {
        state = STATE_COMPLETE;
        ivPlay.setBackgroundResource(R.drawable.btn_player_selector_bg);
        ivNext.performClick();
        animator.cancel();
    }

    public void onStop() {
        state = STATE_STOP;
        ivPlay.setBackgroundResource(R.drawable.btn_player_selector_bg);
        animator.cancel();
    }

    public void onPlay() {
        state = STATE_PLAY;
        ivPlay.setBackgroundResource(R.drawable.btn_pause_selector_bg);
        animator.start();
    }


    private int total;

    public void updateProcessAndTime(int current, int total) {
        this.total = total;
        if (current > 0) {
            tvCurrentTime.setText(generateTime(current));
        }
        if (current > 0) {
            tvTotalTime.setText(generateTime(total));
        }
        long pos = sbStory.getMax() * current / total;
        sbStory.setProgress((int) pos);
    }

    final int STATE_NORMAL = 1;
    final int STATE_PLAY = 2;//播放
    final int STATE_PAUSE = 3;//暂停
    final int STATE_STOP = 4;//停止
    final int STATE_COMPLETE = 5;//完成

    int state = STATE_NORMAL;


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivPlay:
                if (STATE_NORMAL == state || STATE_COMPLETE == state || STATE_STOP == state) {
                    if (null != story && !TextUtils.isEmpty(story.getAudioUrl())) {
                        new Thread(new Runnable() {

                            @Override
                            public void run() {
                                ViewGT.playStory(getContext(), dataList, index);
                            }
                        }).start();
                    } else {
                        isLoad = false;
                    }
                } else if (STATE_PLAY == state) {
                    EventManager.ins().sendEvent(EventTag.GO_PLAY_OR_PAUSE, 0, 0, null);
                } else if (STATE_PAUSE == state) {
                    EventManager.ins().sendEvent(EventTag.GO_PLAY_OR_PAUSE, 0, 0, null);
                }
                break;
            case R.id.ivPrevious:
                EventManager.ins().sendEvent(EventTag.ON_CLICK_PREVIOUS, 0, 0, null);
                break;
            case R.id.ivNext:
                EventManager.ins().sendEvent(EventTag.ON_CLICK_NEXT, 0, 0, null);
                break;
            case R.id.rlActionCollect:
                if (!UserManager.ins().isLogin()) {
                    ViewGT.gotoLoginActivity(getContext());
                    return;
                }
                collectOrCancelCollect();
                break;
            case R.id.rlActionPrise:
                if (!UserManager.ins().isLogin()) {
                    ViewGT.gotoLoginActivity(getContext());
                    return;
                }
                isPrise = !isPrise;
                ivActionPrise.setSelected(isPrise);
                if (isPrise) {
                    story.setAgreeCount(story.getAgreeCount() + 1);
                } else {
                    story.setAgreeCount(story.getAgreeCount() - 1);
                }
                tvPriseCount.setText(String.valueOf(story.getAgreeCount()));
                mHandler.removeCallbacks(priseTask);
                mHandler.postDelayed(priseTask, AppKey.CLICK_REPEAT_TIME);
                break;
            case R.id.ivPlayList:
                EventManager.ins().sendEvent(EventTag.SHOW_PLAY_LIST, 0, 0, null);
                break;
            case R.id.rlActionShare:
                CustomShareBoard shareBoard = new CustomShareBoard(activity, CustomShareBoard.ShareFrom.STORY);
                if (UserManager.ins().isLogin()) {
                    if (story.getUserMsg().getUserId().equals(UserManager.ins().getUserId())) {
                        shareBoard.setDelete(true);
                    }
                }
                String targetUrl = story.getShareUrl();
                String imageUrl = ServerAddressManager.SHARE_DEFAULT_LOGO_URL;
                if (!TextUtils.isEmpty(story.getImage())) {
                    imageUrl = story.getImage();
                }
                String desc = "我在听" + story.getUserMsg().getName() + "的故事";
                String sinaDesc = "很喜欢" + story.getUserMsg().getName() + "的故事《" + story.getTitle() + "》，大家快来听听！ " + story.getShareUrl() + " (解答情感问题，下载@茉莉社区 APP)";

                shareBoard.setShareInfo(story.getTitle(), desc, sinaDesc, imageUrl, imageUrl, targetUrl);
                shareBoard.showPopup(false);
                break;
            case R.id.rlActionComment:
                EventManager.ins().sendEvent(EventTag.DO_SHOW_KEYBOARD, 0, 0, null);
                break;
        }
    }

    public void reset() {
        isLoad = false;
        tvCurrentTime.setText("00:00");
        sbStory.setProgress(0);
    }

    /**
     * 收藏/取消收藏
     */
    public void collectOrCancelCollect() {
        ivActionCollect.setEnabled(false);
        if (null != story.getActionStateMsg() && story.getActionStateMsg().getCollentState() != null) {
            int id = story.getActionStateMsg().getCollentState().intValue();
            API_User.ins().cancelCollect(TAG, UserManager.ins().getUserId(), AppKey.TYPE_STORY, story.getId(), AppKey.FAVORITER_ID, id, new StringResponseCallback() {
                @Override
                public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                    ivActionCollect.setEnabled(true);
                    if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                        ivActionCollect.setSelected(false);
                        story.getActionStateMsg().setCollentState(null);
                    } else {
                        ToastUtil.showToast(errMsg);
                    }
                    return false;
                }
            });
        } else {
            API_User.ins().addCollect(TAG, UserManager.ins().getUserId(), AppKey.TYPE_STORY, story.getId(), AppKey.FAVORITER_ID, new StringResponseCallback() {
                @Override
                public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                    ivActionCollect.setEnabled(true);
                    if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                        CollectResult result = new Gson().fromJson(resultValue, CollectResult.class);
                        if (null != result && null != result.getRes()) {
                            story.getActionStateMsg().setCollentState(result.getRes().getCollent().getId());
                        }
                        ivActionCollect.setSelected(true);
                    } else {
                        ToastUtil.showToast(errMsg);
                    }
                    return false;
                }
            });
        }
    }

    boolean isPrise;
    boolean initPrise;
    Handler mHandler;
    PriseTask priseTask;

    /**
     * 赞任务
     */
    class PriseTask implements Runnable {

        @Override
        public void run() {
            if (initPrise != isPrise) {
                addPriseOrCancelPrise();
            }
        }
    }

    /**
     * 赞/取消赞
     */
    public void addPriseOrCancelPrise() {
        API_User.ins().addPrise(TAG, UserManager.ins().getUserId(), AppKey.TYPE_STORY, story.getId(), AppKey.AGREE, story.getUserMsg().getUserId(), new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                    ActionResult result = new Gson().fromJson(resultValue, ActionResult.class);
                    if (null != result && null != result.getRes()) {
                        if (null == story.getActionStateMsg()) {
                            story.setActionStateMsg(new ActionStateMsg());
                        }
                        story.getActionStateMsg().setAgreeState(result.getRes().getAction().getId());
                    }
                } else {
                    ToastUtil.showToast(errMsg);
                }
                return false;
            }
        });
    }

}
